//
//  MineViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/9/15.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit

class MineViewController: BaseViewController {
    var bgImageView:UIImageView!
    var headIcon:TapImageView!
    var nameLabel:UILabel!
    var loginBtn:UIButton!
    var collectBtn:UIButton!
    var careBtn:UIButton!
    var previewBtn:UIButton!
    var collectLabel:UILabel!
    var careLabel:UILabel!
    var previewLabel:UILabel!
    var contentTable:UITableView!
    let imageNomalArray:[String] = ["order_icon1","order_icon2","order_icon3"]
    let imageSelectArray:[String] = ["TabBar1Sel","TabBar2Sel","TabBar4Sel"]
    let cellImageArray:[String] = ["center_order","center_assets","center_data"]
    let titleArray1:[String] =   ["待付款","待收货","待评价"]
    let titleArray2:[String] =   ["积分"," 旺卡","余额"]
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的"
        self.automaticallyAdjustsScrollViewInsets = false
        self.createTopView()
        self.createRightTableView()
        // Do any additional setup after loading the view.
    }
    func createTopView()->Void{
        let imageRatio:CGFloat = 204/320
        let imageview = UIImageView(frame: CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.width*imageRatio))
        imageview.backgroundColor = commonRedColor
        imageview.image = UIImage(named: "top_bg")
        imageview.userInteractionEnabled = true
        view.addSubview(imageview)
        bgImageView = imageview
        //设置按钮
//        let settingBtn = TabButton(frame: CGRectMake(5, 15, 40, 54))
//        settingBtn.alwaysUnhightlighted = false
//        settingBtn.setTitle("设 置", forState: UIControlState.Normal)
//        settingBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(12)
//        settingBtn.titleLabel?.textAlignment = NSTextAlignment.Center
//        settingBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        settingBtn.setImage(UIImage(named:"TabBar1"), forState: UIControlState.Normal)
//        settingBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
//        imageview.addSubview(settingBtn)
        //消息按钮
        let messageBtn = MyButton(frame: CGRectMake(view.bounds.size.width-5-40, 15, 40, 54))
        messageBtn.imageSize = CGSizeMake(16, 16)
        //        messageBtn.alwaysUnhightlighted = false
        messageBtn.setTitle("消息", forState: UIControlState.Normal)
        messageBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(11)
        messageBtn.titleLabel?.textAlignment = NSTextAlignment.Center
        messageBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        messageBtn.setImage(UIImage(named:"chat-"), forState: UIControlState.Normal)
        messageBtn.addTarget(self, action: "showInfo", forControlEvents: UIControlEvents.TouchUpInside)
        messageBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        imageview.addSubview(messageBtn)
        //头像
        headIcon = TapImageView(frame: CGRectMake(0, 0, 80, 80))
        headIcon.layer.cornerRadius = 40
        headIcon.layer.shadowOffset = CGSizeMake(-1, 1)
        headIcon.layer.shadowColor = UIColor.lightGrayColor().CGColor
        headIcon.layer.shadowOpacity = 0.7
        headIcon.contentMode = UIViewContentMode.ScaleToFill
        headIcon.clipsToBounds = true
//        headIcon.clipsToBounds = true
        headIcon.backgroundColor = UIColor.whiteColor()
        headIcon.center = CGPointMake(imageview.center.x, imageview.center.y-8)
        headIcon.TapCompelete = {[weak self] id in
            if #available(iOS 8.0, *) {
                if GlobalDataHelper.instance.session == nil{
                    return
                }
                let alertController = UIAlertController(title: "上传头像", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
                let takePhotoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Destructive){ action in
                    let imagePick = UIImagePickerController()
                    imagePick.delegate = self
                    imagePick.allowsEditing = true
                    imagePick.sourceType = UIImagePickerControllerSourceType.Camera
                    imagePick.videoQuality = UIImagePickerControllerQualityType.TypeMedium
                    self?.presentViewController(imagePick, animated: true, completion: nil)
                    
                }
                let imageLibAction = UIAlertAction(title: "照片", style: UIAlertActionStyle.Default){ action in
                    let imagePick = UIImagePickerController()
                    imagePick.delegate = self
                    imagePick.allowsEditing = true
                    imagePick.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    self?.presentViewController(imagePick, animated: true, completion: nil)
                }
                let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
                
                alertController.addAction(cancelAction)
                alertController.addAction(imageLibAction)
                alertController.addAction(takePhotoAction)
                self?.presentViewController(alertController, animated: true, completion: nil)
            } else {
                // Fallback on earlier versions
            }
        }
        imageview.addSubview(headIcon)
        //登录注册按钮
        nameLabel = UILabel(frame: CGRectMake(0, CGRectGetMaxY(headIcon.frame)+25, view.bounds.size.width, 30))
        nameLabel.textColor = UIColor.whiteColor()
        nameLabel.font = UIFont.boldSystemFontOfSize(14)
        nameLabel.text = ""
        nameLabel.textAlignment = NSTextAlignment.Center
        imageview.addSubview(nameLabel)
        
        loginBtn = UIButton(frame: CGRectMake(0, 0, 80, 30))
        loginBtn.center = nameLabel.center
        loginBtn.setTitle("登录／注册", forState: UIControlState.Normal)
        loginBtn.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
        loginBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
//        loginBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Highlighted)
        loginBtn.addTarget(self, action: "goLogin", forControlEvents: UIControlEvents.TouchUpInside)
        imageview.addSubview(loginBtn)
//        //格局
//        let line_x = UIView(frame: CGRectMake(0, CGRectGetMaxY(loginBtn.frame)+20, view.bounds.size.width, 1))
//        line_x.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
//        imageview.addSubview(line_x)
//        let line_y1 = UIView(frame: CGRectMake(view.bounds.size.width/3.0, CGRectGetMaxY(line_x.frame), 1, imageview.bounds.size.height-CGRectGetMaxY(line_x.frame)-1))
//        line_y1.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
//        imageview.addSubview(line_y1)
//        let line_y2 = UIView(frame: CGRectMake(view.bounds.size.width*2/3.0, CGRectGetMaxY(line_x.frame), 1, imageview.bounds.size.height-CGRectGetMaxY(line_x.frame)-1))
//        line_y2.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.05)
//        imageview.addSubview(line_y2)
//        //收藏的商品
//        collectBtn = UIButton(frame: CGRectMake(0, CGRectGetMaxY(line_x.frame), view.bounds.size.width/3.0, line_y1.bounds.size.height))
//        imageview.addSubview(collectBtn)
//        collectLabel = UILabel(frame: CGRectMake(0, 5, collectBtn.bounds.size.width, collectBtn.bounds.size.height/2.0-5))
//        collectLabel.textColor = UIColor.whiteColor()
//        collectLabel.font = UIFont.boldSystemFontOfSize(15)
//        collectLabel.text = "10"
//        collectLabel.textAlignment = NSTextAlignment.Center
//        collectBtn.addSubview(collectLabel)
//        let collectInfo = UILabel(frame: CGRectMake(0, CGRectGetMaxY(collectLabel.frame), collectBtn.bounds.size.width, collectBtn.bounds.size.height/2.0-5))
//        collectInfo.textColor = UIColor.whiteColor()
//        collectInfo.font = UIFont.boldSystemFontOfSize(12)
//        collectInfo.text = "收藏的商品"
//        collectInfo.textAlignment = NSTextAlignment.Center
//        collectBtn.addSubview(collectInfo)
//        
//        //关注的品牌
//        careBtn = UIButton(frame: CGRectMake(view.bounds.size.width/3.0, CGRectGetMaxY(line_x.frame), view.bounds.size.width/3.0, line_y1.bounds.size.height))
//        imageview.addSubview(careBtn)
//        careLabel = UILabel(frame: CGRectMake(0, 5, careBtn.bounds.size.width, careBtn.bounds.size.height/2.0-5))
//        careLabel.textColor = UIColor.whiteColor()
//        careLabel.font = UIFont.boldSystemFontOfSize(15)
//        careLabel.text = "10"
//        careLabel.textAlignment = NSTextAlignment.Center
//        careBtn.addSubview(careLabel)
//        let careInfo = UILabel(frame: CGRectMake(0, CGRectGetMaxY(careLabel.frame), collectBtn.bounds.size.width, careBtn.bounds.size.height/2.0-5))
//        careInfo.textColor = UIColor.whiteColor()
//        careInfo.font = UIFont.boldSystemFontOfSize(12)
//        careInfo.text = "收藏的商品"
//        careInfo.textAlignment = NSTextAlignment.Center
//        careBtn.addSubview(careInfo)
//        //浏览记录
//        previewBtn = UIButton(frame: CGRectMake(view.bounds.size.width*2/3.0, CGRectGetMaxY(line_x.frame), view.bounds.size.width/3.0, line_y1.bounds.size.height))
//        imageview.addSubview(previewBtn)
//        previewLabel = UILabel(frame: CGRectMake(0, 5, previewBtn.bounds.size.width, previewBtn.bounds.size.height/2.0-5))
//        previewLabel.textColor = UIColor.whiteColor()
//        previewLabel.font = UIFont.boldSystemFontOfSize(15)
//        previewLabel.text = "10"
//        previewLabel.textAlignment = NSTextAlignment.Center
//        previewBtn.addSubview(previewLabel)
//        let previewInfo = UILabel(frame: CGRectMake(0, CGRectGetMaxY(collectLabel.frame), previewBtn.bounds.size.width, previewBtn.bounds.size.height/2.0-5))
//        previewInfo.textColor = UIColor.whiteColor()
//        previewInfo.font = UIFont.boldSystemFontOfSize(12)
//        previewInfo.text = "浏览记录"
//        previewInfo.textAlignment = NSTextAlignment.Center
//        previewBtn.addSubview(previewInfo)

    }
    func createRightTableView(){
        contentTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(bgImageView.frame), view.bounds.size.width, view.bounds.size.height-tabbarHeight-CGRectGetMaxY(bgImageView.frame)), style: UITableViewStyle.Plain)
        contentTable.separatorStyle = UITableViewCellSeparatorStyle.None
        contentTable.showsHorizontalScrollIndicator = false
        contentTable.showsVerticalScrollIndicator = false
        contentTable.dataSource = self
        contentTable.delegate = self
        let nib = UINib(nibName:"MyCell", bundle: nil)
        contentTable.registerNib(nib, forCellReuseIdentifier:"MyCellID")
//        contentTable.tableHeaderView = bgImageView
        view.addSubview(contentTable)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = true
        if GlobalDataHelper.instance.session != nil{
            self.nameLabel.text = GlobalDataHelper.instance.userInfo?["account"] as? String
            self.headIcon.setImageWithUrl((GlobalDataHelper.instance.userInfo?["user_photo"] as? String)!, defaultImage: nil)
            self.loginBtn.hidden = true
        }
    }
    func showInfo(){
        let ctl = MessageViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func  goLogin(){
        let ctl = LoginViewController()
        ctl.loginSuccess = { userInfo in
            self.nameLabel.text = userInfo?["account"] as? String
            GlobalDataHelper.instance.userId = userInfo?["id"] as? String
            GlobalDataHelper.instance.userInfo = userInfo
            GlobalDataHelper.instance.is_authentication = userInfo?["is_authentication"] as? String
            self.headIcon.setImageWithUrl((userInfo?["user_photo"] as? String)!, defaultImage: nil)
            self.loginBtn.hidden = true
        }
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension MineViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
        print(info[UIImagePickerControllerMediaType])
        var image = info[UIImagePickerControllerEditedImage] as! UIImage
        image = image.scaleTosize(CGSizeMake(300, 300))
        headIcon.image = image
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        let data1:NSData? = UIImagePNGRepresentation(headIcon.image!)
        if data1 == nil{
            self.showTips("错误的图片格式")
            return
        }
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        parameters.setObject(data1!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength), forKey: "userphoto")
        request.requestStart("/user/setUserPhoto", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("设置成功")
                    }
                }
            }
        })
        self.showProcess("正在处理...")
    }
  
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}
extension MineViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return 3
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 45
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 10
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        switch section{
        case 0:
              return 60
        case 1:
              return 60
        case 2:
             return 1
        default:break
        }
    
        return 1
    }
    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCellID", forIndexPath: indexPath) as! MyCell
        var imageName:String?
        var nameText:String?
        var noteInfo:String?
        switch indexPath.section{
        case 0:
            imageName = ""
            nameText = "我的订单"
            noteInfo = "查看全部订单"
        case 1:
            imageName = ""
            nameText = "我的资产"
            noteInfo = ""
        case 2:
            imageName = ""
            nameText = "我的账户"
            noteInfo = ""
        default:break
        }
        if indexPath.section != 1{
            cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        }
        else{
            cell.accessoryType = UITableViewCellAccessoryType.None

        }
        cell.selectImageView.image = UIImage(named: cellImageArray[indexPath.section])
        cell.typeName.text = nameText
        cell.noteInfo.text = noteInfo
        return cell
    }
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        if section == 2{
            return nil
        }
        let footView = MyFootView(frame: CGRectMake(0, 0, tableView.bounds.size.width, 60))
        footView.section = section
        footView.numberOfButton = 3
        footView.imageNomalArray = imageNomalArray
        footView.imageSelectArray = imageSelectArray
        switch section{
        case 0:
            footView.titleArray = titleArray1
//            footView.setBrage(0, brageNumber: 65)
        case 1:
            footView.titleArray = titleArray2
//            footView.setBrage(0, brageNumber: 554)
        default:break
        }
        footView.btnClickHandle = {[weak self,weak footView] (buttonIndex,section) in
            print("第\(section)行，第\(buttonIndex)个按钮")
            if GlobalDataHelper.instance.session == nil{
                self?.goLogin()
                return
            }
            if section == 0{
                let ctl = OrderListViewController()
                switch buttonIndex{
                case 0:
                    ctl.requestOrderType = "pending"
                    ctl.title = "未付款订单"
                case 1:
                    ctl.requestOrderType = "paid"
                    ctl.title = "待收货订单"
                case 2:
                    ctl.requestOrderType = "complete"
                    ctl.title = "已完成订单"
                case 3:
                    ctl.requestOrderType = "complete"
                    ctl.title = "退款/售后订单"
                default:break
                }
                self?.navigationController?.pushViewController(ctl, animated: true)
            }
            if section == 1{
                switch buttonIndex{
                case 0:
                    let ctl = PointQureyViewController()
                    self?.navigationController?.pushViewController(ctl, animated: true)

                case 1:
                    let ctl = WangCardViewController()
                    self?.navigationController?.pushViewController(ctl, animated: true)

                case 2:
                    let ctl = MoneyQureyViewController()
                    self?.navigationController?.pushViewController(ctl, animated: true)
                case 3:
                    let ctl = OrderListViewController()

                default:break
                }
            }
        }
        return footView
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        
        if GlobalDataHelper.instance.session == nil{
            self.goLogin()
            return
        }
        switch indexPath.section{
        case 0:
            let ctl = OrderListViewController()
            ctl.title = "全部订单"
            self.navigationController?.pushViewController(ctl, animated: true)
        case 1:
            break
        case 2:
            let ctl = MyInfomationViewController()
            ctl.logoutSuccess = { [weak self] in
                self?.nameLabel.text = ""
                self?.headIcon.image = nil
                self?.loginBtn.hidden = false
                GlobalDataHelper.instance.session = nil
                GlobalDataHelper.instance.userInfo = nil
//                //清除购物车数据
//                if let nav = GlobalDataHelper.instance.tabCtl?.viewControllers?[3] as? UINavigationController{
//                    if let ctl = nav.viewControllers[0] as? CartViewController {
//                        ctl.cleanData()
//                    }
//                }
            }
            self.navigationController?.pushViewController(ctl, animated: true)
            break
        default:break
        }
    }
}
